package me.helllp.book.concurrent.ch03;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁的使用
 * @author Administrator
 *
 */
public class ReadWriteLockDemo {
	
	@SuppressWarnings("unused")
	private static Lock lock = new ReentrantLock();
	
	private static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
	
	private static Lock readLock = readWriteLock.readLock();
	private static Lock writeLock = readWriteLock.writeLock();
	
	private volatile int value;
	
	public Object handleRead(Lock lock) throws InterruptedException{
		try {
			lock.lock();
			Thread.sleep(1000);
			System.out.println("读取Value=" + value);
			return value;
		} finally {
			lock.unlock();
		}
	}
	
	public void handleWrite(Lock lock, int index) throws InterruptedException{
		try {
			lock.lock();
			Thread.sleep(1000);
			System.out.println("设置Value=" + index);
			value = index;
		} finally {
			lock.unlock();
		}
	}
	
	public static void main(String[] args) {
		final ReadWriteLockDemo demo = new ReadWriteLockDemo();
		Runnable readRunnable = new Runnable() {
			public void run() {
				try {
					demo.handleRead(readLock);
//					demo.handleRead(lock);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		
		Runnable writeRunnable = new Runnable() {
			public void run() {
				try {
					demo.handleWrite(writeLock, new Random().nextInt());
//					demo.handleWrite(lock, new Random().nextInt());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		
		for(int i=0; i<20; i++){
			if(i == 6 || i== 12){
				new Thread(writeRunnable).start();	
			}else{
				new Thread(readRunnable).start();	
			}
		}
	}
}
